#include "kernel_operator.h"

constexpr int32_t TOTAL_LENGTH = 8 * 256;                            // total length of data
constexpr int32_t USE_CORE_NUM = 8;                                   // num of core used
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;         // length computed of each core
constexpr int32_t TILE_NUM = 1;                                       // split data into 8 tiles for each core
constexpr int32_t BUFFER_NUM = 1;                                     // tensor num for each queue
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM; // separate to 2 parts, due to double buffer
constexpr int32_t DATA_BLOCK = 32;

class KernelRenorm
{
public:
    __aicore__ inline KernelRenorm() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, float p, float max_norm, uint32_t dim)
    {
        this->p = p;
        this->max_norm = max_norm;
        this->dim = dim;
        this->block_idx = AscendC::GetBlockIdx();

        
      	if(this->dim == 0){
            sum_params.inner = TILE_LENGTH;
            sum_params.outter = 1;
            sum_params.n = TILE_LENGTH;
        	xGm.SetGlobalBuffer((__gm__ half *)x + BLOCK_LENGTH * this->block_idx, BLOCK_LENGTH);
        	zGm.SetGlobalBuffer((__gm__ half *)z + BLOCK_LENGTH * this->block_idx, BLOCK_LENGTH);
            pipe.InitBuffer(inQueueX, BUFFER_NUM, TILE_LENGTH * sizeof(half));
            pipe.InitBuffer(outQueueZ, BUFFER_NUM, TILE_LENGTH * sizeof(half));
            pipe.InitBuffer(tmpBuffer, TILE_LENGTH * sizeof(float));
            pipe.InitBuffer(tmpBuffer_power, TILE_LENGTH * sizeof(float));
            pipe.InitBuffer(tmpBuffer_sum, sum_params.outter * sizeof(float));
            pipe.InitBuffer(tmpBuffer_norm, sum_params.outter * sizeof(float));
            pipe.InitBuffer(tmpBuffer_output, TILE_LENGTH * sizeof(float));
      	}
        else if(this->dim == 1){
            this->pad_till_length = TILE_LENGTH * DATA_BLOCK / sizeof(half);
            
            sum_params.inner = this->pad_till_length;
            sum_params.outter = 1;
            sum_params.n = this->pad_till_length;
            
			xGm.SetGlobalBuffer((__gm__ half *)x + this->block_idx);
        	zGm.SetGlobalBuffer((__gm__ half *)z + this->block_idx);
            
            
            pipe.InitBuffer(inQueueX, BUFFER_NUM, this->pad_till_length * sizeof(half));
            pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->pad_till_length * sizeof(half));
            pipe.InitBuffer(tmpBuffer, this->pad_till_length * sizeof(float));
            pipe.InitBuffer(tmpBuffer_power, this->pad_till_length * sizeof(float));
            pipe.InitBuffer(tmpBuffer_sum, sum_params.outter);
            pipe.InitBuffer(tmpBuffer_norm, sum_params.outter);
            pipe.InitBuffer(tmpBuffer_output, this->pad_till_length * sizeof(float));
        }


    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = TILE_NUM * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++)
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.AllocTensor<half>();
        if(this->dim == 0){
        	AscendC::DataCopy(xLocal, xGm[progress * TILE_LENGTH], TILE_LENGTH);
      	}
        else if(this->dim == 1){
			AscendC::DataCopyExtParams copyParams{TOTAL_LENGTH, 1 * sizeof(half),
                                                (USE_CORE_NUM - 1) * sizeof(half), 0, 0}; 
        	AscendC::DataCopyPadExtParams<half> padParams{true, 0, DATA_BLOCK/sizeof(half) - 1, 0};
        	AscendC::DataCopyPad(xLocal, this->xGm, copyParams, padParams); 
        }

        inQueueX.EnQue(xLocal);
    }

    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.DeQue<half>();
        AscendC::LocalTensor<half> zLocal = outQueueZ.AllocTensor<half>();
        AscendC::LocalTensor<float> tmp = tmpBuffer.Get<float>();
        AscendC::LocalTensor<float> tmp_power = tmpBuffer_power.Get<float>();
        AscendC::LocalTensor<float> tmp_sum = tmpBuffer_sum.Get<float>();
        AscendC::LocalTensor<float> tmp_norm = tmpBuffer_norm.Get<float>();
        AscendC::LocalTensor<float> tmp_output = tmpBuffer_output.Get<float>();
        
        if(dim==0)
        {
            int16_t index = 0;
            // AscendC::PRINTF("x0: %f", xLocal.GetValue(index));
            // AscendC::DumpTensor(xLocal, 0, TILE_LENGTH  * (DATA_BLOCK / sizeof(half)));

            AscendC::Cast(tmp, xLocal, AscendC::RoundMode::CAST_NONE, TILE_LENGTH);
            // AscendC::DumpTensor(tmp, 0, TILE_LENGTH);
            AscendC::Power(tmp_power, tmp, this->p, TILE_LENGTH);
            // AscendC::PRINTF("tmp_power: %f", tmp_power.GetValue(index));
            // AscendC::DumpTensor(tmp, 0, TILE_LENGTH * (DATA_BLOCK / sizeof(half)));
            AscendC::Sum(tmp_sum, tmp_power, this->sum_params);
            // AscendC::PRINTF("tmp_sum: %f", tmp_sum.GetValue(index));
            // AscendC::DumpTensor(tmp_sum, 0, TILE_LENGTH * (DATA_BLOCK / sizeof(half)));
            AscendC::Power(tmp_norm, tmp_sum, (float)1.0 / this->p, this->sum_params.outter);
            float norm = tmp_norm.GetValue(index);
            // AscendC::PRINTF("norm: %f", norm);
            if (norm < this->max_norm)
            {
                AscendC::Muls(tmp_output, tmp, (float)1.0, TILE_LENGTH);
            }
            else
            {
                AscendC::Muls(tmp_output, tmp, (float)this->max_norm / norm, TILE_LENGTH);
            }
            AscendC::Cast(zLocal, tmp_output, AscendC::RoundMode::CAST_ODD, TILE_LENGTH);
        }
        else
        {
            
            int16_t index = 0;
            // AscendC::PRINTF("x0: %f", xLocal.GetValue(index));
            // AscendC::DumpTensor(xLocal, 0, this->pad_till_length);

            AscendC::Cast(tmp, xLocal, AscendC::RoundMode::CAST_NONE, this->pad_till_length);
            // AscendC::DumpTensor(tmp, 0, this->pad_till_length );
            AscendC::Power<float, false>(tmp_power, tmp, this->p);
            // AscendC::Power(tmp_power, tmp, this->p, TILE_LENGTH * 4);
            // AscendC::PRINTF("tmp_power: %f", tmp_power.GetValue(index));
            // AscendC::DumpTensor(tmp_power, 0, this->pad_till_length);
            AscendC::Sum(tmp_sum, tmp_power, this->sum_params);
            // // AscendC::PRINTF("tmp_sum: %f", tmp_sum.GetValue(index));
            // AscendC::DumpTensor(tmp_sum, 0, this->pad_till_length);
            AscendC::Power(tmp_norm, tmp_sum, (float)1.0 / this->p, this->sum_params.outter);
            float norm = tmp_norm.GetValue(index);
            // AscendC::PRINTF("norm: %f", norm);
            if (norm < this->max_norm)
            {
                AscendC::Muls(tmp_output, tmp, (float)1.0, this->pad_till_length);
            }
            else
            {
                AscendC::Muls(tmp_output, tmp, (float)this->max_norm / norm, this->pad_till_length);
            }
            AscendC::Cast(zLocal, tmp_output, AscendC::RoundMode::CAST_ODD, this->pad_till_length);

        
        }
        outQueueZ.EnQue<half>(zLocal);
        inQueueX.FreeTensor(xLocal);
        
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<half> zLocal = outQueueZ.DeQue<half>();
        if(this->dim == 0){
        	AscendC::DataCopy(zGm[progress * TILE_LENGTH], zLocal, TILE_LENGTH);
      	}
        else if(this->dim == 1){
			AscendC::DataCopyExtParams copyParams{TOTAL_LENGTH, 1 * sizeof(half), 0, (USE_CORE_NUM - 1) * sizeof(half), 0};
        	AscendC::DataCopyPad(this->zGm, zLocal, copyParams); // 从VECIN->GM搬运40Bytes
        }
        outQueueZ.FreeTensor(zLocal);
    }

private:
    float p;
    float max_norm;
    uint32_t dim;
    int32_t block_idx;
    int32_t pad_till_length;

    AscendC::SumParams sum_params;
  
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::GlobalTensor<half> xGm;
    AscendC::GlobalTensor<half> zGm;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuffer;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuffer_power;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuffer_sum;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuffer_norm;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuffer_output;
};

extern "C" __global__ __aicore__ void renorm_custom(GM_ADDR x, GM_ADDR z, float p, float max_norm, uint32_t dim)
{
    KernelRenorm op;
    op.Init(x, z, p, max_norm, dim);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void renorm_custom_do(uint32_t blockDim, void *stream, uint8_t *x, uint8_t *z, float p, float max_norm, uint32_t dim)
{
    renorm_custom<<<blockDim, nullptr, stream>>>(x, z, p, max_norm, dim);
}
#endif